// Setup basic express server
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('socket.io')(server,{cors:true});
const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log('Server listening at port %d', port);
});

//静态文件
app.use(express.static(path.join(__dirname, 'public')));


let numUsers = 0;
//页面开启连接接口
io.on('connection', (socket) => {
  let addedUser = false;

  // when the client emits 'new message', this listens and executes
  //告诉所有人发送的消息
  socket.on('new message', (data) => {
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  //接受用户传过来的名字
  socket.on('add user', (username) => {
    if (addedUser) return;
    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    //然后设置为true,其他人就需要用户名才能进入
    addedUser = true;
    //触发login事件,传入numUsers
    socket.emit('login', {
      numUsers: numUsers
    });
    // 告诉所有用户人数和名字
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // 当客户端发出“打字”时，我们将其播放给别人
  socket.on('typing', () => {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // 当客户端发出“停止打字”时，我们将其播放给别人
  socket.on('stop typing', () => {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // 当用户断开连接。执行此操作
  socket.on('disconnect', () => {
    if (addedUser) {
      --numUsers;
      // 告诉所有人离开
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
